package cn.drh.charging.order.config;


import cn.drh.charging.order.mqtt.MqttConsumer;
import cn.drh.charging.order.mqtt.MqttContext;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @ClassName MqttConfiguration
 * @Description TODO
 * @Author renhong~Deng
 * @Date 2025/5/28 9:36
 * @Version 1.0
 */

@Configuration
public class MqttConfiguration {

    /**
     * 用户名 这些配置类的信息 应该放到 配置文件或者nacos中
     */
    private String userName = "admin";
    /**
     * 密码
     */
    private String password = "admin123456";
    //mqtt服务地址
    private String host = "tcp://127.0.0.1:1883";
    /**
     * 客户端id
     */
    private String clientId = "order_service_client_"+getRandomId();

    private Integer getRandomId() {
        return (int) (Math.random() * 1000000);
    }

    @Autowired
    private MqttContext mqttContext;

    @Bean
    public MqttClient getMqttClient() throws Exception {
        //通过连接地址和客户端id和emqx进行连接
        //客户端id 目的是要告诉我们的服务器 谁在连接它
        MqttClient mqttClient = new MqttClient(host, clientId);
        //连接后需要登陆账号密码
        MqttConnectOptions conopts = new MqttConnectOptions();
        conopts.setUserName(userName);
        conopts.setPassword(password.toCharArray());
        //自动重连
        conopts.setAutomaticReconnect(true);
        //版本号设置
        conopts.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1);
        //清理会话session
        conopts.setCleanSession(true);
        //设置回调方法
        mqttClient.setCallback(new MqttConsumer(mqttContext, mqttClient));
        //基于上面的配置连接
        mqttClient.connect(conopts);
        return mqttClient;
    }
}
